package edu.xmut.yuepai.gateway.filter;

import cn.hutool.core.util.StrUtil;
import edu.xmut.yuepai.common.constant.AuthConstants;
import edu.xmut.yuepai.common.result.RCode;
import edu.xmut.yuepai.common.template.RedisCacheTemplate;
import edu.xmut.yuepai.common.utils.JwtUtil;
import edu.xmut.yuepai.gateway.properties.CustomAuthProperties;
import edu.xmut.yuepai.gateway.utils.MonoUtils;
import edu.xmut.yuepai.model.dto.RedisUserDTO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Objects;

import static edu.xmut.yuepai.common.constant.RedisConstants.USER_INFO_KEY;

@Slf4j
@Component
@EnableConfigurationProperties(CustomAuthProperties.class)
public class TokenGlobalFilter implements GlobalFilter, Ordered {

    @Resource
    private CustomAuthProperties customAuthProperties;

    @Resource
    private RedisCacheTemplate redisCacheUtils;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取请求路径
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        log.info("本次请求路径：{}", path);
        // 2.判断是否需要拦截
        if (isExclude(path)) {
            // 不拦截直接跳过
            return chain.filter(exchange);
        }
        // 3.获取请求头中的header
        String token = "";
        List<String> tokens = request.getHeaders().get(AuthConstants.TOKEN_HEADER);
        // 4.校验token是否为空
        if (CollectionUtils.isEmpty(tokens)) {
            return MonoUtils.setResponse(exchange, RCode.TOKEN_NOT_EXIST, "Token不存在");
        }
        token = tokens.get(0);
        if (StrUtil.isBlank(token)) {
            return MonoUtils.setResponse(exchange, RCode.TOKEN_NOT_EXIST, "Token不存在");
        }
        // 5.校验token
        String userIdStr;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userIdStr = claims.getSubject();
        } catch (ExpiredJwtException e) {
            return MonoUtils.setResponse(exchange, RCode.TOKEN_EXPIRED, "Token已过期，请重新登录");
        } catch (MalformedJwtException e) {
            return MonoUtils.setResponse(exchange, RCode.TOKEN_INVALID, "非法Token");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 6.查询redis中的用户实体，判断是否被踢下线
        String key = USER_INFO_KEY + userIdStr;
        RedisUserDTO user = redisCacheUtils.get(key);
        if (Objects.isNull(user)) {
            return MonoUtils.setResponse(exchange, RCode.TOKEN_EXPIRED, "Token已过期，请重新登录");
        }
        // 7.只允许同一账号在一个地方登录，判断是否被挤下线
        // if (!Objects.equals(user.getCurrentToken(), token)) {
        //    return MonoUtils.setResponse(exchange, "该账号已在其他地方登录"");
        // }
        // 8.传递用户身份信息到下游微服务模块
        String finalUserIdStr = userIdStr;
        exchange.mutate()
                .request(builder -> builder.header(AuthConstants.USER_ID_HEADER, finalUserIdStr))
                .build();
        return chain.filter(exchange);
    }

    private boolean isExclude(String path) {
        for (String excludePathPattern : customAuthProperties.getExcludePathPatterns()) {
            // 匹配成功
            if (antPathMatcher.match(excludePathPattern, path)) {
                return true;
            }
        }
        // 循环结束，匹配失败
        return false;
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
